package com.itheima.until;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.Base64;
import java.util.Objects;

public class Encryptor {
    static MessageDigest messageDigest = null;
    static final int SALT_LEN = 12;

    static {
        try {
            messageDigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
    private Encryptor() {
        throw new AssertionError("nonono");
    }


    public static String encrypt(String password){
        Objects.requireNonNull(password);

        byte[] salt = new byte[SALT_LEN];
        new SecureRandom().nextBytes(salt);

        messageDigest.update(password.getBytes());
        messageDigest.update(salt);

        byte[] digest = messageDigest.digest();

        byte[] encryptBytes = new byte[SALT_LEN + digest.length];

        System.arraycopy(salt,0,encryptBytes,0,SALT_LEN);
        System.arraycopy(digest,0,encryptBytes,SALT_LEN,digest.length);


        return Base64.getEncoder().encodeToString(encryptBytes);
    }

    public static boolean validate(String password,String encryt){

        return password != null && encryt != null && _verify(password, encryt);
    }

    private static boolean _verify(String password, String encryt) {
        byte[] encryptBytes = Base64.getDecoder().decode(encryt);
        byte[] salt = Arrays.copyOf(encryptBytes, SALT_LEN);

        byte[] digest = Arrays.copyOfRange(encryptBytes, SALT_LEN, encryptBytes.length);

        messageDigest.update(password.getBytes());
        messageDigest.update(salt);

        byte[] digesting = messageDigest.digest();

        return Arrays.equals(digest, digesting);
    }

    public static void main(String[] args) {
        String encrypt = encrypt("123");
        System.out.println("encrypt(\"123\") = " + encrypt);

        boolean validate = validate("123", "luGFaw/HhGTe5y88S99zQpj4gtAx+MKfwYo1+g==");
        System.out.println("validate = " + validate);


    }
}
